package com.kenliang.javase.concurrent.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author KenLiang
 * @description:Lock类除了提供了ReentrantLock的锁以外，还提供了ReentrantReadWriteLock的锁。读写锁分成两个锁，一个锁是读锁，一个锁是写锁。读锁与读锁之间是共享的，读锁与写锁之间是互斥的，写锁与写锁之间也是互斥的。
 * @date Created in 6:08 PM 2019/3/13.
 */
public class ReadWriteService {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();


    public void read(){
        try {
            lock.readLock().lock();
            System.out.println("获得读锁" + Thread.currentThread().getName() +
                    " " + System.currentTimeMillis());
            for(int i=0;i<20;i++){
                System.out.println("read :"+i);
            }
        } finally {
            lock.readLock().unlock();
        }
    }

    public void write(){
        try {
            lock.writeLock().lock();
            System.out.println("获得写锁" + Thread.currentThread().getName() +
                    " " + System.currentTimeMillis());
            for(int i=0;i<20;i++){
                System.out.println("write :"+i);
            }
        } finally {
            lock.writeLock().unlock();
        }
    }


    public static void main(String[] args) {
        ReadWriteService readWriteService = new ReadWriteService();
        Thread t1 =  new Thread(readWriteService::read);
        Thread t11 =  new Thread(readWriteService::read);
        Thread t2 = new Thread(readWriteService::write);
        Thread t22 = new Thread(readWriteService::write);

        t22.start();
        t1.start();
        t11.start();
        t2.start();
    }

}
